package com.tbs.easyhomemoneyserver.dao.providers

import com.tbs.easyhomemoneyserver.form.HomeSearchForm
import com.tbs.easyhomemoneyserver.utils.SysUtils

class HomeProvider {
    fun findByForm(homeSearchForm: HomeSearchForm): String {
        val stringBuilder = StringBuilder(
            "SELECT\n" + "\th.* ,\n" + "\t(phm.child_id) as parentId ,\n" + "\tsu.`name` as parentName\n" + "FROM\n" + "\thome h\n" + "\tLEFT JOIN home_member phm  ON h.id=phm.home_id  AND phm.`enable`='1' AND phm.member_type='0' " + "LEFT JOIN sys_user su ON phm.child_id=su.id "
        );
        if (!homeSearchForm.memberId.isNullOrEmpty()) {
            stringBuilder.append(
                " JOIN home_member hm ON h.id = hm.home_id " + "AND hm.child_id IN (" + SysUtils.ColToString(
                    homeSearchForm.memberId!!.toList(),
                    { return@ColToString it.toString() }) + ") AND hm.`enable`='1' AND hm.member_type='1'  "
            )
        }
        stringBuilder.append(" where  h.delete_flag =0 ")
        if (!homeSearchForm.homeId.isNullOrEmpty()) {
            stringBuilder.append(
                " AND h.id in (" + SysUtils.ColToString(homeSearchForm.homeId!!.toList(), { it.toString() }) + ")"
            )
        }
        if (!homeSearchForm.vagueHomeName.isNullOrEmpty()) {
            val it = homeSearchForm.vagueHomeName
            stringBuilder.append(" AND h.home_name LIKE '$it%' ")
        }
        if (!homeSearchForm.accurateHomeName.isNullOrEmpty()) {
            val it = homeSearchForm.accurateHomeName
            stringBuilder.append(" AND h.home_name = '$it'")
        }
        homeSearchForm.createDateBefore?.let { stringBuilder.append(" AND h.create_date <= '$it'") }
        homeSearchForm.createDateAfter?.let { stringBuilder.append(" AND h.create_date >= '$it'") }
        stringBuilder.append(" group by \th.id,\n" + "\tphm.child_id,\n" + "\tsu.`name`")
        return stringBuilder.toString()
    }
}